// 新增、修改体检机构
<template>
  <el-form :model="form" class="add-form">
    <div class="add-left">
      <el-form-item>
        <span><i>*</i>机构名称 :</span>
        <el-input v-model="form.organName" autocomplete="off" />
      </el-form-item>
      <el-form-item>
        <span><i>*</i>分支名称 :</span>
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>
      <el-form-item>
        <span><i>*</i>机构ID :</span>
        <el-input autocomplete="off" disabled placeholder="系统自动生成" />
      </el-form-item>
      <el-form-item>
        <span><i>*</i>是否启用</span>
        <el-switch
          :active-value="1"
          :inactive-value="2"
          v-model="form.isUsed"
        />
      </el-form-item>
      <el-form-item>
        <span><i>*</i>地址 :</span>
        <el-input autocomplete="off" v-model="form.location" />
      </el-form-item>
      <el-form-item class="logo">
        <span><i>*</i>机构图片 :</span>
        <el-upload
          :before-upload="beforeUpload"
          ref="upload"
          action="http://172.16.129.235:8080/admin/upload/image"
          :headers="getUploadHeaders"
          method="post"
          list-type="picture-card"
          :auto-upload="false"
          :limit="1"
          :on-exceed="handleExceed"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item class="upload">
        <span>小提示 :</span
        ><i class="tips">只能上传jpg/png文件，且不超过10000kb</i>
        <el-button plain size="small" @click="submitUpload">
          点击上传
        </el-button>
        <el-button plain size="small" @click="remove_img" v-if="show_remove">
          移除图片
        </el-button>
      </el-form-item>
    </div>
    <div class="add-right">
      <el-form-item class="sel-city">
        <span><i>*</i>所在城市 :</span>
        <el-select
          v-model="form.provinceId"
          placeholder="选择省"
          @change="searchcities(form.provinceId)"
        >
          <el-option
            v-for="(province, index) in provinceoptions"
            :key="province.provinceId"
            :label="province.provinceName"
            :value="province.provinceId"
          />
        </el-select>
        <el-select v-model="form.cityId" placeholder="选择市">
          <el-option
            v-for="(city, index) in cityoptions"
            :key="city.cityId"
            :label="city.cityName"
            :value="city.cityId"
          />
        </el-select>
      </el-form-item>
      <el-form-item class="type">
        <span><i>*</i>机构类型 :</span>
        <el-select v-model="form.type" placeholder="选择机构类型">
          <el-option
            v-for="(institu, index) in institu_options"
            :key="institu.id"
            :label="institu.type"
            :value="institu.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item class="attribute">
        <span><i>*</i>机构属性 :</span>
        <el-checkbox
          v-model="form.status"
          label="免预约"
          :true-label="1"
          :false-label="0"
          name="type"
        />
      </el-form-item>
      <el-form-item>
        <span><i>*</i>电话 :</span>
        <el-input
          autocomplete="off"
          placeholder="输入11位手机号码"
          v-model="form.phone"
        />
      </el-form-item>
      <el-form-item class="coordinate">
        <span><i>*</i>坐标 :</span>
        <el-input autocomplete="off" placeholder="北纬" v-model="form.north" />
        <el-input autocomplete="off" placeholder="东经" v-model="form.east" />
      </el-form-item>
      <el-form-item class="saved" v-if="show_img">
        <span><i>*</i>目前机构图片 :</span>
        <el-image
          style="width: 100px; height: 100px"
          :src="form.imgUrl"
          fit="fill"
        />
      </el-form-item>
    </div>
  </el-form>
</template>

<script lang="ts" setup>
import { ref, reactive, h, computed, onMounted, watch } from "vue";
import { ElTable, ElMessage, ElMessageBox, genFileId } from "element-plus";
import type {
  UploadInstance,
  UploadProps,
  UploadRawFile,
  UploadUserFile,
} from "element-plus";
import { InfoFilled, Plus, UploadFilled } from "@element-plus/icons-vue";
import "element-plus/theme-chalk/index.css";
import zhCn from "element-plus/dist/locale/zh-cn.mjs";
import { city_search, search_all, type_all } from "../apis/phyorgan";
import { usephyorganStore } from "./../stores/phyorgan";
const store = usephyorganStore();

// 监测添加表单的值的变化
let form = reactive({
  organName: "",
  provinceId: null, //选择的省名
  cityId: null, //选择的市名
  name: "", //分支名称
  type: null, //机构类型
  status: null, //机构属性
  isUsed: 1, //是否启用
  phone: "", //电话
  location: "", //地址
  north: "", //北纬
  east: "", //东经
  imgUrl: "", //图片路径
});

interface ProvinceOption {
  //省数组的类型
  provinceName: string;
  provinceId: number;
}

interface CityOption {
  //市数组的类型
  cityName: string;
  cityId: number;
}
let cityoptions: CityOption[] = reactive([]);
let institu_options: any = reactive([]); //机构类型选择
let prop = defineProps({
  provinceoptions: {
    type: Array as PropType<ProvinceOption[]>,
    required: true,
  },
  show_img: Boolean,
  updateform: Object,
  show_remove: Boolean,
});

// 通过省获取市
let search_cities = (id) => {
  city_search({ id }).then((res) => {
    // console.log(res.data);
    cityoptions.length = 0; //市的下拉框数据重置
    cityoptions.push(...res.data.data);
    // console.log(cityoptions);
  });
};

// 选择省获取市(change事件)
let searchcities = (id) => {
  city_search({ id }).then((res) => {
    // console.log(res.data);
    cityoptions.length = 0; //市的下拉框数据重置
    cityoptions.push(...res.data.data);
    // console.log(cityoptions);
    form.cityId = cityoptions.length ? cityoptions[0].cityId : "";
  });
};

// 列表查询所有
let searchall = () => {
  search_all({}).then((res) => {
    // console.log(res.data.data);
  });
};

searchall();

// 列表查询所有机构类型，赋值给下拉框
let typeall = () => {
  type_all({}).then((res) => {
    // console.log(res.data.data);
    let res_arr = res.data.data;
    res_arr.forEach((el) => {
      institu_options.push({
        id: el.organTypeId,
        type: el.organTypeName,
        isDeleted: el.isDeleted,
      });
    });
  });
};

typeall();
// console.log(prop.provinceoptions);
// 图片上传
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
// 移除当前图片
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

// 查看当前图片放大效果
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

//文件上传之前的钩子函数
const beforeUpload = (file) => {
  // 自定义验证逻辑
  // 如果验证失败，返回 false 阻止上传
  // 如果验证通过，返回 true 允许上传
  //大多数浏览器将 JPG 文件的 MIME 类型设置为 "image/jpeg"
  if (file.type !== "image/png" && file.type !== "image/jpeg") {
    ElMessage({
      showClose: true,
      message: "请选择jpg或者png的图片文件",
      type: "warning",
    });
    return false;
  }
  if (file.size / 1024 / 1024 > 10) {
    ElMessage({
      showClose: true,
      message: "图片大小不能超过10MB",
      type: "warning",
    });
    return false;
  }
  // 验证通过，允许文件上传
  return true;
};

// 更新文件列表，只保留最新选择的文件
const upload = ref<UploadInstance>();
const handleExceed: UploadProps["onExceed"] = (files) => {
  // fileList = fileList.slice(-1);
  // console.log(files[0]);
  // console.log(fileList[0]);
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value!.handleStart(file);
};

//请求头携带token
let getUploadHeaders = reactive({
  token: sessionStorage.getItem("token"),
});

// 点击上传
const submitUpload = () => {
  // console.log(upload.value);
  upload.value!.submit();
};

//移除图片
let remove_img = () => {
  form.imgUrl = "";
};

// 上传成功响应事件(文件上传成功后的回调函数)
let handleUploadSuccess = (res) => {
  console.log(res.data);
  form.imgUrl = res.data;
  ElMessage({
    showClose: true,
    message: "文件上传成功",
    type: "success",
  });
};

// 上传失败响应事件(文件上传失败后的回调函数)
let handleUploadError = (err) => {
  // console.log("错误信息:", err);
  ElMessage({
    showClose: true,
    message: "文件上传失败",
    type: "info",
  });
};
//及时同步地改变pinia里面的addform
watch(form, (newValue) => {
  // console.log("form 变化了:", newValue);
  store.up_addform(newValue); //把store中的addform赋值成新的表单对象
  store.update_form(newValue); //把store中的updateform赋值成新的表单对象
});

//及时响应修改父组件点击修改项的变化
watch(prop.updateform, (newValue) => {
  Object.keys(form).forEach((key) => {
    //先把表单对象的值清空
    form[key] = null;
  });
  Object.assign(form, newValue);
  // console.log(form);
  // 某些返回"string"字符串的变为空
  form.location == "string"
    ? (form.location = "")
    : (form.location = form.location);
  form.north == "string" ? (form.north = "") : (form.north = form.north);
  form.east == "string" ? (form.east = "") : (form.east = form.east);
  search_cities(form.provinceId);
});

// 正则验证手机号码
</script>

<style lang="less" scoped>
.add-form.el-form {
  display: flex;
  justify-content: space-between;
}

// .add-form.el-form .el-form-item {
//   width: 45%;
// }

// 添加机构表单左右两个板块
.add-left,
.add-right {
  // display: flex;
  // flex-direction: column;
  // justify-content: flex-start;
  width: 49%;
}

.add-left > .el-form-item,
.add-right > .el-form-item {
  display: flex;
  align-items: center;
  height: 30px;
  margin-top: 22px;
}

.add-right > .el-form-item.attribute {
  flex-wrap: nowrap;
}

.add-right > .el-form-item .el-checkbox-group {
  // text-align: right;
  // display: flex;
  max-width: 200px;
}

// 机构图片单独设置margin，以及宽度等
.add-left > .el-form-item.logo {
  margin-top: 100px;
  width: 200%;
  display: flex;
}

.add-right > .el-form-item.saved {
  margin-top: 100px;
}

// 上传提示文字+按钮
.el-form-item.upload {
  margin-top: 70px;
  width: 200%;
  display: flex;
  align-items: center;
}

// 小提示文字
.el-form-item.upload i.tips {
  color: rgb(198, 29, 29);
}

// 上传按钮
.el-form-item.upload .el-button {
  margin-left: 2rem;
}

// 所有新增里面的字体右对齐
.add-form .el-form-item span {
  width: 6.6rem;
  text-align: right;
  margin-right: 20px;
}

.add-form .el-form-item .el-input,
.add-form .el-form-item.type .el-select {
  width: 192px;
  // margin-left: 20px;
}

// 所在城市下拉框,坐标输入框
.add-form .el-form-item.sel-city .el-select,
.add-form .el-form-item.coordinate .el-input {
  width: 92px;
  margin-right: 8px;
}

// 添加机构里面的红色*号
.add-left > .el-form-item span > i,
.add-right > .el-form-item span > i {
  color: rgb(250, 83, 83);
  display: inline-block;
  transform: translateX(-10px);
}
</style>
